//
//  RVideoDetailsViewController.m
//  iMoive
//
//  Created by 侯伟 on 2021/8/27.
//

#import "RVideoDetailsViewController.h"
#import "SDCycleScrollView.h"
#import "MoiveDramaDeriesView.h"
#import "RVideoItemView.h"
#import "SDCycleScrollView.h"
#import "RDeviceControlView.h"
#import "RProjectionScreenControlView.h"

#import "QXAdvertManager.h"

#import <SJMediaCacheServer/SJMediaCacheServer.h>
#import <SJVideoPlayer/SJVideoPlayer.h>
#import <SJUIKit/NSAttributedString+SJMake.h>
#import <Masonry/Masonry.h>
#import <MediaPlayer/MediaPlayer.h>
#import <SJBaseVideoPlayer/SJPLPlayerPlaybackController.h>
#import <AVKit/AVKit.h>

#import "RVideoDetailsRequest.h"
#import "RVideoDetailsBannerRequest.h"
#import "RCacheManager.h"

#import "RVideoIntroduceViewController.h"
#import "RVideoPlayItemViewController.h"
#import "RVideoCacheItemViewController.h"
#import "RFeedbackViewController.h"
#import "ShareHanler.h"

static SJControlLayerIdentifier RProjectionScreenControlLayerIdentifier = 301;
static SJControlLayerIdentifier RDeviceControlLayerIdentifier = 302;

@interface RVideoDetailsViewController ()<QXAdvertDelegate,MoiveDramaDeriesDelegate,AVRoutePickerViewDelegate,RDeviceControlLayerViewControllerDelegate,RProjectionScreenControlViewDelegate>{
    NSIndexPath* _currentIndex;
    BOOL _isUpdate;
}

@property(nonatomic,strong)MyLinearLayout *rootLayout;

//播放器承载
@property(nonatomic,strong)UIView *containerView;

/// 下方视图承载
@property(nonatomic,strong)UIView *contentLayout;

//轮播提示
//@property(nonatomic,strong)MyRelativeLayout *noticeLayout;
@property(nonatomic,strong)SDCycleScrollView *noticeBannerView;

/// 视频信息
@property(nonatomic,strong)MyRelativeLayout *moiveInfoLayout;
@property(nonatomic,strong)UILabel* nameLb;//名称
@property(nonatomic,strong)UILabel* scoreLb;//评分等等
@property(nonatomic,strong)UIButton* introducBtn;//查看简介按钮

/// 操作按钮
@property(nonatomic,strong)MyFlowLayout *btnLayout;
@property(nonatomic,strong)UIButton *shareBtn;//分享
@property(nonatomic,strong)UIButton *collectBtn;//收藏
@property(nonatomic,strong)UIButton *feedbackBtn;//反馈

/// 广告
@property(nonatomic,strong)UIView *adBannerView;

/// 剧集
@property(nonatomic,strong)MyLinearLayout *urlsLayout;

/// 推荐影片
@property(nonatomic,strong)MyLinearLayout *recommendLayout;
@property(nonatomic,strong)MyFlowLayout *videosLayout;



#pragma mark -- player
@property(nonatomic, strong)SJVideoPlayer *player;
@property(nonatomic, strong)id<SJControlLayerSwitcherObserver> switchgetObserver;

/// 播放地址
@property(nonatomic,strong)RVideoDetailsData* videoDetails;


@property(nonatomic,strong)NSArray<MoiveDramaDeriesView*>* dramaItems;

@end

@implementation RVideoDetailsViewController

- (BOOL)shouldAutorotate {
    return NO;
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    MAPPDelegate.allowOrentitaionRotation = YES;
}
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [self.player vc_viewDidAppear];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    MAPPDelegate.allowOrentitaionRotation = NO;
    [self.player vc_viewWillDisappear];
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    [self.player vc_viewDidDisappear];
}

- (void)loadView{
    [super loadView];
    
    // 根视图
    MyLinearLayout *rootLayout = [MyLinearLayout linearLayoutWithOrientation:(MyOrientation_Vert)];
    rootLayout.backgroundColor = COLOR_WHITE;
    rootLayout.myMargin = 0;
    [self.view addSubview:rootLayout];
    _rootLayout = rootLayout;
    
    //播放视图
    UIView *playView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, PX(210)+IPHONE_TOP_SAFEINSET)];
    playView.backgroundColor = UIColor.blackColor;
    playView.myMargin = 0;
    playView.myHeight = PX(210)+IPHONE_TOP_SAFEINSET;
    playView.myWidth = SCREEN_WIDTH;
    [rootLayout addSubview:playView];
    
    UIView *containerView = [[UIView alloc] initWithFrame:CGRectMake(0, IPHONE_TOP_SAFEINSET, SCREEN_WIDTH, PX(210))];
    containerView.myTop = IPHONE_TOP_SAFEINSET;
    containerView.myHeight = PX(210);
    containerView.myHorzMargin = 0;
    [playView addSubview:containerView];
    _containerView = containerView;
    
    //轮播提示
    SDCycleScrollView *noticeBannerView = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, 0, SCREEN_WIDTH - 40, PX(30)) delegate:NULL placeholderImage:nil];
    noticeBannerView.titleLabelTextColor = COLOR_ORANGE;
    noticeBannerView.titleLabelBackgroundColor = COLOR_ORANGE_LIGHT;
    noticeBannerView.scrollDirection = UICollectionViewScrollDirectionVertical;
    noticeBannerView.onlyDisplayText = YES;
    noticeBannerView.autoScrollTimeInterval = 3.0;
    noticeBannerView.layer.cornerRadius = 4;
    noticeBannerView.layer.masksToBounds = YES;
    noticeBannerView.backgroundColor = COLOR_ORANGE_LIGHT;
    noticeBannerView.myHeight = PX(30);
    noticeBannerView.myHorzMargin = 20;
    noticeBannerView.myVertMargin = 10;
    [rootLayout addSubview: noticeBannerView];
    _noticeBannerView = noticeBannerView;
    
    //下方滚动先行视图
    UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:self.view.bounds];
    scrollView.backgroundColor = COLOR_BACKGEOUND;
    scrollView.showsHorizontalScrollIndicator = NO;
    scrollView.showsVerticalScrollIndicator = NO;
    scrollView.myMargin = 0;
    scrollView.weight = 1.0;
    [rootLayout addSubview:scrollView];
    
    MyLinearLayout *contentLayout = [MyLinearLayout linearLayoutWithOrientation:(MyOrientation_Vert)];
    contentLayout.myTop = 0;
    contentLayout.myHorzMargin = 0;
    contentLayout.subviewVSpace = 10;
    contentLayout.padding = UIEdgeInsetsMake(10, 0, 0, 0);
    contentLayout.heightSize.lBound(scrollView.heightSize, 10, 1);
    [scrollView addSubview:contentLayout];
    _contentLayout = contentLayout;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [QXAdvertManager manager].delegate = self;
    
    [self loadVideoAd];
    
    [self setupViews];
    
    [self setupPlayer];
    
    [self updateViews];
    
    [self requestNoticeInfo];
    
    [self loadBannerAd];
}

#pragma mark --ad
//全屏广告
- (void)loadVideoAd{
    [[QXAdvertManager manager] loadVideoAdWithRootViewController:self];
}

//banner广告
- (void)loadBannerAd{
    [[QXAdvertManager manager] loadBannerAdWithRootViewController:self superView:self.adBannerView];
}

#pragma mark -player
//player
- (void)setupPlayer{

    SJVideoPlayer* player = [SJVideoPlayer player];
    [self.containerView addSubview:player.view];
    [player.view mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.offset(0);
    }];
    _player = player;
    
    player.playbackController = SJPLPlayerPlaybackController.new;
    
    player.presentView.placeholderImageView.image = [UIImage imageNamed:@"details_playground_bg"];
    
    //网络状态提示
    player.defaultEdgeControlLayer.disabledPromptWhenNetworkStatusChanges = NO;
    player.defaultEdgeControlLayer.fixesBackItem = NO;
    
    //其他
    player.videoGravity = AVLayerVideoGravityResizeAspect;
    player.pauseWhenAppDidEnterBackground = YES;
    player.resumePlaybackWhenAppDidEnterForeground = YES;
    player.resumePlaybackWhenPlayerHasFinishedSeeking = YES;
    
    //旋转
    player.rotationManager.disabledAutorotation = NO;
    player.rotationManager.autorotationSupportedOrientations = SJOrientationMaskAll;
    
    //长显示
    [player.controlLayerAppearManager keepAppearState];
    
    //长按快进
    player.gestureControl.supportedGestureTypes |= SJPlayerGestureTypeMask_LongPress;
    player.rateWhenLongPressGestureTriggered = 2.0;
    player.defaultEdgeControlLayer.draggingProgressPopupView.style = SJDraggingProgressPopupViewStyleFullscreen;
    
    //移除画中画
    if (@available(iOS 14.0, *)) {
        self.player.defaultEdgeControlLayer.automaticallyShowsPictureInPictureItem = NO;
    }
    
    //投屏
    SJEdgeControlButtonItem* item = [[SJEdgeControlButtonItem alloc] initWithImage:[UIImage imageNamed:@"details_tv"] target:self action:@selector(projectionScreen:) tag:201];
    [player.defaultEdgeControlLayer.topAdapter addItem:item];
    [player.defaultEdgeControlLayer.topAdapter reload];
    [player controlLayerNeedAppear];
    
    //底部时间
    [player.defaultEdgeControlLayer.bottomAdapter removeItemForTag:SJEdgeControlLayerBottomItem_Separator];
    [player.defaultEdgeControlLayer.bottomAdapter exchangeItemForTag:SJEdgeControlLayerBottomItem_DurationTime withItemForTag:SJEdgeControlLayerBottomItem_Progress];
    
    //下一集
    SJEdgeControlButtonItem *playNextItem = [[SJEdgeControlButtonItem alloc] initWithImage:[UIImage imageNamed:@"details_play_next"] target:self action:@selector(playNext:) tag:201];
    playNextItem.insets = SJEdgeInsetsMake(-10, 0);
    [player.defaultEdgeControlLayer.bottomAdapter insertItem:playNextItem rearItem:SJEdgeControlLayerBottomItem_CurrentTime];
    [player.defaultEdgeControlLayer.bottomAdapter reload];
    
    WeakSelf
    //设备控制层
    [self.player.switcher addControlLayerForIdentifier:RDeviceControlLayerIdentifier lazyLoading:^id<SJControlLayer> _Nonnull(SJControlLayerIdentifier identifier) {
        StrongSelf
        if (!strongSelf) return nil;
        RDeviceControlView *deviceControl = [RDeviceControlView new];
        deviceControl.delegate = strongSelf;
        return deviceControl;
    }];
    
    //投屏控制层
    [self.player.switcher addControlLayerForIdentifier:RProjectionScreenControlLayerIdentifier lazyLoading:^id<SJControlLayer> _Nonnull(SJControlLayerIdentifier identifier) {
        StrongSelf
        if (!strongSelf) return nil;
        RProjectionScreenControlView* projectionScreenControlLayer = [RProjectionScreenControlView new];
        projectionScreenControlLayer.delegate = strongSelf;
        return projectionScreenControlLayer;
    }];
    
    self.switchgetObserver = self.player.switcher.getObserver;
    self.switchgetObserver.playerDidEndSwitchControlLayer = ^(id<SJControlLayerSwitcher>  _Nonnull switcher, id<SJControlLayer>  _Nonnull controlLayer) {
        StrongSelf
        if (!strongSelf) return;
        if(switcher.currentIdentifier == RProjectionScreenControlLayerIdentifier){
            strongSelf.player.resumePlaybackWhenAppDidEnterForeground = NO;
        }else{
            strongSelf.player.resumePlaybackWhenAppDidEnterForeground = YES;
        }
    };
    

    self.player.playbackObserver.durationDidChangeExeBlock = ^(__kindof SJBaseVideoPlayer * _Nonnull player) {
        StrongSelf
        if(!strongSelf){
            return;
        }
        [Queue asyncMain:^{
            [[RLMRealm defaultRealm] transactionWithBlock:^{
                strongSelf.video.totalTime = player.duration;
                [[RLMRealm defaultRealm] addOrUpdateObject:strongSelf.video];
            }];
        }];
    };
    
    self.player.playbackObserver.currentTimeDidChangeExeBlock = ^(__kindof SJBaseVideoPlayer * _Nonnull player) {
        StrongSelf
        if(!strongSelf){
            return;
        }
        [Queue asyncMain:^{
            [[RLMRealm defaultRealm] transactionWithBlock:^{
                strongSelf.video.currentTime = player.currentTime;
                [[RLMRealm defaultRealm] addOrUpdateObject:strongSelf.video];
            }];
        }];
    };
    
    self.player.playbackObserver.playbackDidFinishExeBlock = ^(__kindof SJBaseVideoPlayer * _Nonnull player) {
        StrongSelf
        if(!strongSelf){
            return;
        }
        [Queue asyncMain:^{
            [strongSelf playNextURL];
        }];
    };
    
    self.player.playbackObserver.didSeekToTimeExeBlock = ^(__kindof SJBaseVideoPlayer * _Nonnull player, CMTime time) {
        [SJMediaCacheServer.shared setActive:YES];
    };
}

//设置播放路径
- (void)setAssetURLWithUrlObj:(RVideoUrlObj *)urlObj{

    NSURL* URL = [NSURL URLWithString:urlObj.url_m3u8];
    if(!URL)
        return;
    
    [self stop];
    
    NSString* title = [NSString stringWithFormat:@"%@ %@",self.video.name,urlObj.url_info];
    
    NSURL *playbackURL = [SJMediaCacheServer.shared playbackURLWithURL:URL];
    
    SJVideoPlayerURLAsset* assetURL = [[SJVideoPlayerURLAsset alloc] initWithTitle:title URL:playbackURL playModel:NULL];
    assetURL.pl_playerOptions = PLPlayerOption.defaultOption;
    
    self.player.URLAsset = assetURL;
    
    //缓存5M
    [SJMediaCacheServer.shared prefetchWithURL:URL preloadSize:5*1024*1024];
}

//播放
- (void)play{
    
    [self refreshDramaDeriesView];
    
    if(self.player.URLAsset){
        [self.player play];
        [SJMediaCacheServer.shared setActive:YES];
    }
}


//停止
- (void)stop{
    if(self.player.isPlaying){
        [self.player stop];
        [SJMediaCacheServer.shared setActive:NO];
    }
}

- (void)setPlayURLAtIndexPath:(NSIndexPath *)indexPath play:(BOOL)play{
    
    if(indexPath.section >= self.videoDetails.top.count)
        return;
    RVideoUrlGroup* group = self.videoDetails.top[indexPath.section];
    
    if(indexPath.row >= group.urls.count)
        return;
    
    RVideoUrlObj* videoUrl = group.urls[indexPath.row];
    
    //设置播放地址与缓存地址
    [self setAssetURLWithUrlObj:videoUrl];
    
    if(play){
        [self play];
    }
    _currentIndex = indexPath;
    
    [self.player.switcher switchControlLayerForIdentifier:SJControlLayer_Edge];
    
    [[RLMRealm defaultRealm] transactionWithBlock:^{
        
        self.video.isPlayed = YES;
        self.video.lastPlayDate = [NSDate date];
        self.video.col = indexPath.col;
        self.video.row = indexPath.row;
        self.video.dramaName = videoUrl.url_info;
    }];
}

//刷新
- (void)refreshDramaDeriesView{
    //显示当先选择的播放剧集
    for (int i = 0 ; i < self.dramaItems.count; i++) {
        MoiveDramaDeriesView* item = self.dramaItems[i];
        if(_currentIndex.section != item.urlGroup.index){
            [item playAt:-1];
        }else{
            [item playAt:_currentIndex.row];
        }
    }
}


- (void)playNextURL{
    
    [self loadVideoAd];
    
    [self loadBannerAd];
    
    NSIndexPath* nextIndex = [NSIndexPath indexPathForCol:self->_currentIndex.col inRow:self->_currentIndex.row+1];
    
    [self setPlayURLAtIndexPath:nextIndex play:NO];
}

#pragma mark -- action

//投屏
- (void)projectionScreen:(id)sender{
    [self.player.switcher switchControlLayerForIdentifier:RDeviceControlLayerIdentifier];
}

//下一集
- (void)playNext:(id)sender{
    [self playNextURL];
}


//简介
- (void)intrduceClicked:(UIButton*)sender{
    RVideoIntroduceViewController* intrduce = [RVideoIntroduceViewController new];
    intrduce.movie = self.video;
    [intrduce presentOverViewController:self];
}

//分享
- (void)shareClicked:(UIButton*)sender{
    [ShareHanler shareAPP];
}

//收藏
- (void)collectClicked:(UIButton*)sender{
    
    sender.selected = !sender.selected;
    
    [[RLMRealm defaultRealm] transactionWithBlock:^{
        self.video.isCollect = sender.selected;
        [[RLMRealm defaultRealm] addOrUpdateObject:self.video];
    }];
    if(sender.selected){
        [Toast toast:@"收藏成功"];
    }else{
        [Toast toast:@"取消收藏"];
    }
}

//反馈
- (void)feedBackClicked:(UIButton*)sender{
    RFeedbackViewController *feedback = [RFeedbackViewController new];
    [UIViewController showViewController:feedback animated:YES];
}

#pragma mark  -- RDeviceControlLayerViewControllerDelegate
///
/// 点击空白区域的回调
///
- (void)tappedBlankAreaOnTheControlLayer:(id<SJControlLayer>)controlLayer{
    [self.player.switcher switchControlLayerForIdentifier:SJControlLayer_Edge];
}

///
/// 选择播放设备
///
- (void)choiseDeviceOnTheControlLayer:(id<SJControlLayer>)controlLayer device:(CLUPnPDevice*)device{
    
    if(_currentIndex.section >= self.videoDetails.top.count)
        return;
    RVideoUrlGroup* group = self.videoDetails.top[_currentIndex.section];
    
    if(_currentIndex.row >= group.urls.count)
        return;
    
    RVideoUrlObj* videoUrl = group.urls[_currentIndex.row];
    
    id<SJControlLayer> projectionScreenControlLayer = [self.player.switcher controlLayerForIdentifier:RProjectionScreenControlLayerIdentifier];
    RProjectionScreenControlView* tvcontrolLayer = (RProjectionScreenControlView*)projectionScreenControlLayer;
    tvcontrolLayer.device = device;
    tvcontrolLayer.url = videoUrl.url_m3u8;
    tvcontrolLayer.title = videoUrl.url_info;
    tvcontrolLayer.duration = self.player.duration;

    [self.player.switcher switchControlLayerForIdentifier:RProjectionScreenControlLayerIdentifier];
    
    [self.player pause];
}

#pragma mark -- RProjectionScreenControlViewDelegate
///
/// 点击返回
///
- (void)backItemClickOnTheControlLayer:(id<SJControlLayer>)controlLayer{
    [self.player stop];
    [self closeViewControllerAnimated:YES];
}

- (void)stopItemClickOnTheControlLayer:(id<SJControlLayer>)controlLayer{
    [self.player play];
    [self.player.switcher switchControlLayerForIdentifier:SJControlLayer_Edge];
}

/// 切换
- (void)switchItemClickOnTheControlLayer:(id<SJControlLayer>)controlLayer{
    [self.player.switcher switchControlLayerForIdentifier:RDeviceControlLayerIdentifier];
}


#pragma mark -- <MoiveDramaDeriesView>
- (void)playUrl:(NSString *)urlStr atIndexPath:(NSIndexPath *)indexPath{
    
    [self loadVideoAd];
    
    [self loadBannerAd];
    
    [self setPlayURLAtIndexPath:indexPath play:NO];
}

- (void)choiseDramaForPurpose:(NSInteger)purpose atIndex:(NSInteger)index{
    
    RVideoUrlGroup* group = self.videoDetails.top[index];
    

    if(purpose == 1){
        RVideoPlayItemViewController* choiseController = [RVideoPlayItemViewController new];
        choiseController.urlGroup = group;
        choiseController.currentIndex = _currentIndex;
        choiseController.selectBlock = ^(id  _Nullable obj, NSIndexPath * _Nonnull indexPath) {
            
            [self loadVideoAd];
            
            [self loadBannerAd];
            
            [self setPlayURLAtIndexPath:indexPath play:NO];
        };
        [choiseController presentOverViewController:self];
    }else{
        RVideoCacheItemViewController* choiseController = [RVideoCacheItemViewController new];
        choiseController.urlGroup = group;
        choiseController.video = self.video;
        [choiseController presentOverViewController:self];
    }
}

#pragma mark -- <QXadverSDKDelegate>
//获取广告类型
- (void)QXAdTypeDidLoaded:(ADType)adType success:(BOOL)success{
    if(!success){
        if(adType == ADType_Video){
            [self play];
            if(self.dramaItems.count){
                
                
                [self.dramaItems[0] playAt:self->_currentIndex.row];
            }
        }else{
            self.adBannerView.visibility = MyVisibility_Gone;
        }
    }
}

//加载成功
- (void)QXAdDidLoaded:(ADType)adType adChannel:(ADChannel)adChannel ad:(id)ad{
    if(adType == ADType_Banner){
        self.adBannerView.visibility = MyVisibility_Visible;
    }
}

//加载失败
- (void)QXAdLoadFaild:(ADType)adType adChannel:(ADChannel)adChannel error:(NSError *)error{
    if(adType == ADType_Banner){
        self.adBannerView.visibility = MyVisibility_Gone;
    }
    else if(adType == ADType_Video){
        [self play];
    }
}

//展示失败
- (void)QXAdDisplayFaild:(ADType)adType adChannel:(ADChannel)adChannel error:(NSError *)error{
    if(adType == ADType_Banner){
        self.adBannerView.visibility = MyVisibility_Gone;
    }
    else if(adType == ADType_Video){
        [self play];
    }
}

//关闭
- (void)QXAdDidClosed:(ADType)adType adChannel:(ADChannel)adChannel ad:(id)ad{
    if(adType == ADType_Banner){
        self.adBannerView.visibility = MyVisibility_Gone;
    }
    else if(adType == ADType_Video){
        [self play];
    }
}

#pragma mark -- request

- (void)requestUrls{
    RVideoDetailsRequest* request = [RVideoDetailsRequest new];
    request.v_id = self.video.id;
    request.action = @"g_u";
    
    [RequestOperation encryptedRequest:request quite:YES callBack:^(HResponse * _Nullable response) {
        [[response success:^(RVideoDetailsData*  _Nonnull data) {
            self.videoDetails = data;
            
            [self setupUrls];

            [self setupRecommend];
            
        }] failure:^(APIError * _Nonnull error) {
            [Toast toast:@"获取视频信息错误"];
            [self closeViewControllerAnimated:YES];
        }];
    }];
}

- (void)requestNoticeInfo{
    RVideoDetailsBannerRequest* request = [RVideoDetailsBannerRequest new];
    request.action = @"g_r";
    [RequestOperation encryptedRequest:request quite:YES callBack:^(HResponse * _Nullable response) {
        [[response success:^(NSArray<RVideoDetailsBanner*>*  _Nonnull data) {
   
            NSMutableArray* titles = [NSMutableArray array];
            for (RVideoDetailsBanner* notice in data) {
                [titles addObject:notice.title];
            }
            if(titles.count > 0){
                self.noticeBannerView.visibility = MyVisibility_Visible;
                self.noticeBannerView.titlesGroup = titles;
            }else{
                self.noticeBannerView.visibility = MyVisibility_Gone;
            }
        }] failure:^(APIError * _Nonnull error) {
            self.noticeBannerView.visibility = MyVisibility_Gone;
        }];
    }];
}

#pragma mark  --updateViews

- (void)updateViews{
    self.nameLb.text = self.video.name;//名称
    [self.nameLb sizeToFit];
    
    NSString* text = [NSString stringWithFormat:@"%@ · %@ · %@",self.video.year,self.video.channel3_id,self.video.channel2_id];
    self.scoreLb.text = text;//评分等等
    [self.scoreLb sizeToFit];
    
    //收藏情况
    [self setupCollect];
    
    //播放地址
    [self requestUrls];
}

#pragma mark  --setupViews
- (void)setupViews{
    
    //影片信息
    MyRelativeLayout *moiveInfoLayout = [MyRelativeLayout new];
    moiveInfoLayout.backgroundColor = COLOR_WHITE;
    moiveInfoLayout.padding = UIEdgeInsetsMake(16, 16, 16, 16);
    moiveInfoLayout.myHorzMargin = 0;
    moiveInfoLayout.myTop = 0;
    moiveInfoLayout.myHeight = MyLayoutSize.wrap;
    [self.contentLayout addSubview:moiveInfoLayout];
    _moiveInfoLayout = moiveInfoLayout;
    
    //名称
    UILabel* nameLb = [UILabel lableWithFont:FONT_FIT(15) color:COLOR_BLACK_DARK text:NULL];
    nameLb.myTop = nameLb.myLeft = 0;
    nameLb.myRight = 50;
    [moiveInfoLayout addSubview:nameLb];
    _nameLb = nameLb;
    
    //信息
    UILabel* scoreLb = [UILabel lableWithFont:FONT_FIT(12) color:COLOR_GRAY_BASE text:NULL];
    scoreLb.topPos.equalTo(nameLb.bottomPos).offset(10.0);
    scoreLb.myLeft = 0;
    [scoreLb sizeToFit];
    [moiveInfoLayout addSubview:scoreLb];
    _scoreLb = scoreLb;
    
    //查看简介
    UIButton* introducBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [introducBtn setTitleColor:COLOR_GRAY_BASE forState:UIControlStateNormal];
    [introducBtn setTitle:@"简介＞" forState:UIControlStateNormal];
    introducBtn.titleLabel.font = FONT_FIT(12);
    [introducBtn addTarget:self action:@selector(intrduceClicked:) forControlEvents:UIControlEventTouchUpInside];
    introducBtn.myRight = 0;
    introducBtn.centerYPos.equalTo(nameLb.centerYPos);
    [introducBtn sizeToFit];
    [moiveInfoLayout addSubview:introducBtn];
    _introducBtn = introducBtn;
    
    MyFlowLayout *flowLayout = [MyFlowLayout flowLayoutWithOrientation:MyOrientation_Horz arrangedCount:1];
    flowLayout.myHeight = PX(30);
    flowLayout.topPos.equalTo(self.scoreLb.bottomPos).offset(16);
    flowLayout.gravity = MyGravity_Horz_Around;
    flowLayout.myHorzMargin = 0;
    [moiveInfoLayout addSubview:flowLayout];
    _btnLayout = flowLayout;
    
    UIButton* sharebtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [sharebtn setImage:[UIImage imageNamed:@"details_share"] forState:UIControlStateNormal];
    [sharebtn addTarget:self action:@selector(shareClicked:) forControlEvents:UIControlEventTouchUpInside];
    sharebtn.mySize = CGSizeMake(PX(70), PX(30));
    [sharebtn sizeToFit];
    [flowLayout addSubview:sharebtn];
    _shareBtn = sharebtn;
    
    UIButton* collectBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [collectBtn setImage:[UIImage imageNamed:@"details_collect_n"] forState:UIControlStateNormal];
    [collectBtn setImage:[UIImage imageNamed:@"details_collect_h"] forState:UIControlStateSelected];
    [collectBtn addTarget:self action:@selector(collectClicked:) forControlEvents:UIControlEventTouchUpInside];
    collectBtn.mySize = CGSizeMake(PX(70), PX(30));
    [collectBtn sizeToFit];
    [flowLayout addSubview:collectBtn];
    _collectBtn = collectBtn;
    
    UIButton* feedbackbtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [feedbackbtn setImage:[UIImage imageNamed:@"details_feedback"] forState:UIControlStateNormal];
    [feedbackbtn addTarget:self action:@selector(feedBackClicked:) forControlEvents:UIControlEventTouchUpInside];
    feedbackbtn.mySize = CGSizeMake(PX(70), PX(30));
    [feedbackbtn sizeToFit];
    [flowLayout addSubview:feedbackbtn];
    _feedbackBtn = feedbackbtn;
    
    //广告
    UIView *adBannerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, PX(64))];
    adBannerView.backgroundColor= COLOR_WHITE;
    adBannerView.myMargin = 0;
    adBannerView.myHeight = PX(64);
    [self.contentLayout addSubview:adBannerView];
    _adBannerView = adBannerView;
    adBannerView.visibility = MyVisibility_Gone;
    
    //剧集
    MyLinearLayout *urlsLayout = [MyLinearLayout linearLayoutWithOrientation:(MyOrientation_Vert)];
    urlsLayout.backgroundColor = COLOR_WHITE;
    urlsLayout.myMargin = 0;
    urlsLayout.myHeight = MyLayoutSize.wrap;
    urlsLayout.padding = UIEdgeInsetsMake(8, 0, 8, 0);
    [self.contentLayout addSubview:urlsLayout];
    _urlsLayout = urlsLayout;
    
    //推荐
    MyLinearLayout *recommendLayout = [MyLinearLayout linearLayoutWithOrientation:(MyOrientation_Vert)];
    recommendLayout.backgroundColor = COLOR_WHITE;
    recommendLayout.myMargin = 0;
    recommendLayout.myHeight = MyLayoutSize.wrap;
    [self.contentLayout addSubview:recommendLayout];
    _recommendLayout = recommendLayout;
    recommendLayout.visibility = MyVisibility_Gone;
    
    UILabel* recommendTitle = [UILabel lableWithFont:FONTBOLD(17) color:COLOR_BLACK_DARK text:@"猜你喜欢"];
    recommendTitle.myHorzMargin = recommendTitle.myTop = 16;
    [recommendLayout addSubview:recommendTitle];
    
    // 流式布局
    MyFlowLayout *videosLayout = [MyFlowLayout flowLayoutWithOrientation:MyOrientation_Vert arrangedCount:3];
    videosLayout.backgroundColor = COLOR_WHITE;
    videosLayout.myHeight = MyLayoutSize.wrap;
    videosLayout.subviewVSpace = 10;
    videosLayout.subviewHSpace = 10;
    videosLayout.gravity = MyGravity_Horz_Between;
    videosLayout.padding = UIEdgeInsetsMake(16, 16, 16, 16);
    videosLayout.myMargin = 0;
    [videosLayout setSubviewsSize:PX(105) minSpace:8 maxSpace:CGFLOAT_MAX centered:NO];
    [recommendLayout addSubview:videosLayout];
    _videosLayout = videosLayout;
}

//是否收藏
- (void)setupCollect{
    RLMResults* ret = [RVideoObj objectsWhere:@"id = %@",self.video.id];
    if(ret.count){
        RVideoObj* obj = ret.firstObject;
        self.collectBtn.selected = obj.isCollect;
    }else{
        self.collectBtn.selected = NO;
    }
}

//设置剧集信息
- (void)setupUrls{
    
    [self.urlsLayout removeAllSubviews];
    
    NSMutableArray* items = [NSMutableArray array];
    
    for (int i = 0 ; i < self.videoDetails.top.count; i++) {
        RVideoUrlGroup* urlGroup = self.videoDetails.top[i];
        urlGroup.index = i;
        
        MoiveDramaDeriesView* item = [MoiveDramaDeriesView new];
        item.delegate = self;
        item.urlGroup = urlGroup;
        item.myMargin = 0;
        [self.urlsLayout addSubview:item];
        [items addObject:item];
    }
    self.dramaItems = items;
    
    RLMResults* ret = [[RVideoObj objectsWhere:@"id = %@ and isPlayed = %d",self.video.id,YES] sortedResultsUsingKeyPath:@"lastPlayDate" ascending:NO];
    if(ret.count){
        RVideoObj* his = ret.firstObject;
        [self setPlayURLAtIndexPath:[NSIndexPath indexPathForCol:his.col inRow:his.row] play:NO];
    }else{
        [self setPlayURLAtIndexPath:[NSIndexPath indexPathForCol:0 inRow:0] play:NO];
    }
}

//推荐影视
- (void)setupRecommend{
    
    [self.videosLayout removeAllSubviews];
    if(!self.videoDetails.bottom.count){
        self.recommendLayout.visibility = MyVisibility_Gone;
        return;
    }else{
        self.recommendLayout.visibility = MyVisibility_Visible;
    }
    
    for (int i = 0; i < self.videoDetails.bottom.count; i++) {
        RVideoObj* movie = self.videoDetails.bottom[i];
        RVideoItemView* item = [RVideoItemView new];
        item.movie = movie;
        WeakSelf
        item.playBlock = ^(id  _Nullable obj) {
            StrongSelf
            if(strongSelf){
                strongSelf.video = obj;
                [strongSelf loadVideoAd];
                [strongSelf loadBannerAd];
                [strongSelf updateViews];
            }
        };
        [self.videosLayout addSubview:item];
    }
}


- (void)dealloc{
    self.player.muted = YES;
    self.player.assetURL = NULL;
    [self stop];
}

@end




